<!--
    props属性值：
    limits: number,决定上传图片张数的限制

    defineExpose：
    fileList: el-upload的fileList
    getFileExposed方法： 返回图片的raw数组，可以放入formData中
-->

<template>
    <el-upload ref="upload" v-model:file-list="fileList" class="upload-demo" action="#" :limit="limits" :auto-upload="false"
        list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
        :on-change="handleFileChange" :on-exceed="handleExceed">
        <!-- :on-success="handleFileSuccess" -->
        <el-icon>
            <Plus />
        </el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible" :close-on-click-modal="false">
        <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;" />
        <template #header>
            <el-button @click="dialogVisible = false">Close</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
//上传图片模块
import { ref } from 'vue'
import { uploadBaseProps, type UploadInstance, type UploadProps, UploadFiles } from 'element-plus'
import { RefSymbol } from '@vue/reactivity';
import { toRaw } from '@vue/reactivity'

const props = defineProps({
    limits: {
        type: Number,
        required: true
    }
});

const upload = ref<UploadInstance>()
const limit = ref(props.limits)
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
var fileExposed;//接收uploadFiles

//文件删除时绑定的函数
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFiles)
}

//文件预览函数
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

//文件改变时绑定的函数
const handleFileChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    console.log('文件改变');
    fileExposed = toRaw(uploadFiles);
}

//父组件获取文件数组的函数
const getFileExposed = () => {
    //console.log(fileExposed);
    return fileExposed;
}

const handleExceed = (uploadFile, uploadFiles) => {
    // 当文件数量超过限制时触发
    alert(`只能上传最多${limit.value}张图片，请重新选择`);
}

const clearFile = () => {
    if (upload.value) {
        upload.value.clearFiles();
    }
}

//将fileList暴露给父组件
defineExpose({
    fileList,
    dialogImageUrl,
    getFileExposed,
    clearFile
})
</script>